package com.jl.juc.volitale;

import java.util.concurrent.TimeUnit;

public class SynchVolitaileDemo3 {

    private static boolean flag = true;
    private static Object lock = new Object();

    /**
     *  测试synchronized也具备可见性，
     * @param args
     */
    public static void main(String[] args) throws InterruptedException {

        new Thread(()->{
            System.out.println(Thread.currentThread().getName()  + "-------- flag = " + flag);
                while (flag){
                    //此处加锁的目的是为了保证flag的可见性
                    synchronized (lock) {

                    }
                }
            System.out.println(Thread.currentThread().getName()  + "----end------ flag = " + flag);
        }, "C").start();
        //保证线程C先启动
        TimeUnit.SECONDS.sleep(2);
        flag = false;
        System.out.println(Thread.currentThread().getName() + "设置flag = " + flag);
    }

}


